const utils = require('j7/utils');
const app = require('j7/app');
const error = require('j7/error');
const modelsFactory = require('./models/factory');
const serviceFactory = require('./services/factory');
const metaFactory = require('./metadata/factory');

class Session {

  constructor(req, rsp) {
    this.req = req;
    this.rsp = rsp;
    this.nowTime = utils.getUtcTime();
    this.useConns = {};
  }

  async destory() {
    if (this.user) {
      await this.user.destory();
    }
    for (let key in this.useConns) {
      this.useConns[key].release();
    }
    //console.log(new Error().stack);
    this.useConns = null;
  }

  getNowTime() {
    return this.nowTime;
  }

  getNowDaySeconds() {
    return this.getNowDaySeconds(this.getNowTime());
  }

  getDaySeconds(utcTime) {

  }

  rspErr(errCode, errMsg) {
    utils.rspErr(this.rsp, errCode, errMsg);
  }

  rspOk() {
    utils.rspOk(this.rsp);
  }

  rspData(data) {
    utils.rspData(this.rsp, data);
  }

  dieErr(errCode, errMsg) {
    this.rspErr(errCode, errMsg);
  }

  throwError(errCode, errMsg) {
    throw new error.InternalError(errCode, errMsg);
  }

  request(name, defVal = null) {
    return name in this.req.query ? this.req.query[name] : defVal;
  }

  requestToJson() {
    return utils.jsonEncode(this.req.query);
  }

  createModel(name) {
    return modelsFactory.create(name, this);
  }

  createService(name) {
    return serviceFactory.create(name, this);
  }

  getMeta(name, key) {
    return metaFactory.getMetaByKey(name, key);
  }

  callMetaStatic(name, method, ...args) {
    return metaFactory.callMetaStatic(name, method, this, ...args);
  }

  traverseMetaList(name, cb) {
    return metaFactory.traverseMetaList(name, cb);
  }

  callMetaFactory(name, ...args) {
    return metaFactory[name](this, ...args);
  }

}

module.exports = Session;
